import 'package:aero_frisbee/app/state/app_cache_state.dart';
import 'package:aero_frisbee/app_route.dart';
import 'package:aero_frisbee/core/extension/string_ext.dart';
import 'package:aero_frisbee/gen/assets.gen.dart';
import 'package:aero_frisbee/pages/entry/app_tab_page.dart';
import 'package:aero_frisbee/pages/modues/message/pages/message/message_detail/viwe_model/af_message_detail_view_model.dart';
import 'package:aero_frisbee/pages/modues/post/af_create_post/view_model/af_create_post_view_model.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';

import 'views/af_mine_posts_cell.dart';

class AfMinePage extends ConsumerStatefulWidget {
  const AfMinePage({super.key});
  @override
  ConsumerState<ConsumerStatefulWidget> createState() => _AfMinePageState();
}

class _AfMinePageState extends ConsumerState<AfMinePage>
    with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;
  @override
  Widget build(BuildContext context) {
    super.build(context);
    final postList = ref.watch(afMyCreatedPostsListServiceProvider);
    final loginUserInfo = ref.watch(curlUserInfoProvider)?.userInfoModel;
    final userInfo = ref
        .watch(getUserInfoFutureProvider(userId: loginUserInfo?.userId ?? ''))
        .maybeWhen(
          orElse: () => null,
          data: (data) => data,
        );
    return Scaffold(
      backgroundColor: const Color(0xffffffff),
      appBar: AppBar(
          leadingWidth: 0,
          leading: const SizedBox(
            width: 0,
          ),
          title: Align(
            alignment: Alignment.centerLeft,
            child: GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () {
                context.pushNamed(RouteUri.appPurchase);
              },
              child: Container(
                decoration: BoxDecoration(
                  color: const Color(0xff454545),
                  borderRadius: BorderRadius.circular(13),
                ),
                margin: const EdgeInsets.only(
                  left: 0,
                ),
                padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 2),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Assets.icons.iconGiftsCount.image(width: 18),
                    Flexible(
                      child: Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 4),
                        child: Text(
                          '${loginUserInfo?.availableCoins ?? 0}',
                          style: const TextStyle(
                            color: Color(0xffffffff),
                            fontWeight: FontWeight.normal,
                            fontSize: 16,
                          ),
                          textAlign: TextAlign.center,
                          overflow: TextOverflow.ellipsis,
                          maxLines: 1,
                        ),
                      ),
                    ),
                    Assets.images.mine.giftsDetailBtn.image(width: 18)
                  ],
                ),
              ),
            ),
          ),
          actions: [
            GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () {
                Keys.tabKey.currentState?.showHomeEndDrawerPages();
              },
              child: Padding(
                padding:
                    const EdgeInsets.symmetric(horizontal: 20, vertical: 8),
                child: Assets.icons.iconMore.image(width: 28),
              ),
            ),
          ]),
      extendBodyBehindAppBar: true,
      body: SingleChildScrollView(
        scrollDirection: Axis.vertical,
        child: Stack(
          children: [
            AspectRatio(
              aspectRatio: 1125 / 564,
              child: Assets.images.mine.profileBg.image(),
            ),
            Column(
              children: [
                SizedBox(
                  height: MediaQuery.of(context).padding.top,
                ),
                const SizedBox(
                  height: kToolbarHeight,
                ),
              ],
            ),
            Column(
              children: [
                AspectRatio(
                  aspectRatio: 1125 / 345,
                  child: Container(
                    decoration: const BoxDecoration(),
                  ),
                ),
                Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Expanded(
                      flex: 82,
                      child: SizedBox(
                        height: 20,
                      ),
                    ),
                    Expanded(
                      flex: 88,
                      child: AspectRatio(
                        aspectRatio: 1,
                        child: FractionallySizedBox(
                          widthFactor: 1,
                          heightFactor: 1,
                          child: Stack(
                            children: [
                              GestureDetector(
                                behavior: HitTestBehavior.opaque,
                                onTap: () {
                                  context.pushNamed(RouteUri.customerService);
                                },
                                child: Container(
                                  decoration: const BoxDecoration(),
                                  padding: const EdgeInsets.all(12),
                                  child: LayoutBuilder(
                                    builder: (BuildContext context,
                                        BoxConstraints constraints) {
                                      return ClipRRect(
                                        borderRadius: BorderRadius.circular(
                                            constraints.maxHeight / 2),
                                        child: AspectRatio(
                                          aspectRatio: 1,
                                          child: CachedNetworkImage(
                                            imageUrl: userInfo?.avatarUrl ?? '',
                                            fit: BoxFit.fill,
                                            placeholder: (context, url) =>
                                                const Material(
                                              color: Color(0xffF2F5F9),
                                              child: Center(
                                                child: SizedBox(
                                                  width: 25,
                                                  height: 25,
                                                  child:
                                                      CircularProgressIndicator(
                                                    strokeWidth: 2,
                                                    color: Color(0xffADADAD),
                                                    backgroundColor:
                                                        Colors.white,
                                                  ),
                                                ),
                                              ),
                                            ),
                                            errorWidget: (context, url,
                                                    error) =>
                                                const CircularProgressIndicator(
                                              strokeWidth: 2,
                                              color: Color(0xffADADAD),
                                              backgroundColor: Colors.white,
                                            ),
                                          ),
                                        ),
                                      );
                                    },
                                  ),
                                ),
                              ),
                              Positioned(
                                bottom: 13,
                                right: 13,
                                child: Assets.icons.iconUpdateAvatarBtn
                                    .image(width: 26),
                              )
                            ],
                          ),
                        ),
                      ),
                    ),
                    Expanded(
                      flex: 205,
                      child: Column(
                        children: [
                          const SizedBox(
                            height: 60,
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              const SizedBox(
                                width: 70,
                              ),
                              Expanded(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    GestureDetector(
                                      behavior: HitTestBehavior.opaque,
                                      onTap: () {
                                        context.pushNamed(
                                            RouteUri.customerService);
                                      },
                                      child: Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.start,
                                        children: [
                                          Text(
                                            userInfo?.nickname ?? '',
                                            style: const TextStyle(
                                              color: Color(0xff202020),
                                              fontWeight: FontWeight.w500,
                                              fontSize: 18,
                                            ),
                                            textAlign: TextAlign.left,
                                            overflow: TextOverflow.ellipsis,
                                            maxLines: 1,
                                          ),
                                          const SizedBox(
                                            width: 10,
                                          ),
                                          Assets.icons.iconProfileEditBtn
                                              .image(width: 16)
                                        ],
                                      ),
                                    ),
                                    const SizedBox(
                                      height: 10,
                                    ),
                                    RichText(
                                      text: TextSpan(
                                        text: 'ID：${userInfo?.userId}',
                                        style: TextStyle(
                                          color: const Color(0xff000000)
                                              .withOpacity(0.3),
                                          fontWeight: FontWeight.normal,
                                          fontSize: 14,
                                        ),
                                        children: [
                                          const WidgetSpan(
                                            child: SizedBox(width: 4),
                                          ),
                                          TextSpan(
                                            text: ' copy',
                                            recognizer: TapGestureRecognizer()
                                              ..onTap = () {
                                                //
                                                Clipboard.setData(
                                                  ClipboardData(
                                                    text: "${userInfo?.userId}",
                                                  ),
                                                );
                                                "copied".toast();
                                              },
                                          ),
                                        ],
                                      ),
                                    )
                                  ],
                                ),
                              ),
                              const SizedBox(
                                width: 20,
                              ),
                            ],
                          )
                        ],
                      ),
                    )
                  ],
                ),
                const SizedBox(
                  height: 20,
                ),
                const Align(
                  alignment: Alignment.topLeft,
                  child: Padding(
                    padding: EdgeInsets.only(left: 20),
                    child: Text(
                      'Gift',
                      style: TextStyle(
                        color: Color(0xff000000),
                        fontWeight: FontWeight.w500,
                        fontSize: 16,
                      ),
                      textAlign: TextAlign.left,
                      overflow: TextOverflow.ellipsis,
                      maxLines: 1,
                    ),
                  ),
                ),
                Container(
                  margin:
                      const EdgeInsets.symmetric(horizontal: 20, vertical: 16),
                  child: Assets.images.mine.profileGiftsBg.image(),
                ),
                const SizedBox(
                  height: 10,
                ),
                const Align(
                  alignment: Alignment.topLeft,
                  child: Padding(
                    padding: EdgeInsets.only(left: 20),
                    child: Text(
                      'post',
                      style: TextStyle(
                        color: Color(0xff000000),
                        fontWeight: FontWeight.w500,
                        fontSize: 16,
                      ),
                      textAlign: TextAlign.left,
                      overflow: TextOverflow.ellipsis,
                      maxLines: 1,
                    ),
                  ),
                ),
                if (postList.isNotEmpty)
                  GridView.custom(
                    shrinkWrap: true,
                    physics: const NeverScrollableScrollPhysics(),
                    padding: const EdgeInsets.symmetric(
                        horizontal: 20, vertical: 20),
                    scrollDirection: Axis.vertical,
                    gridDelegate:
                        const SliverGridDelegateWithFixedCrossAxisCount(
                            crossAxisCount: 2, //横轴三个子widget
                            mainAxisSpacing: 10,
                            crossAxisSpacing: 10,
                            childAspectRatio: 162 / 233 //宽高比为1时，子widget
                            ),
                    childrenDelegate: SliverChildBuilderDelegate(
                      (context, position) {
                        final item = postList[position];
                        return AfMinePostsCell(item);
                      },
                      childCount: postList.length,
                    ),
                  )
                else
                  Container(
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(8),
                    ),
                    padding: const EdgeInsets.all(20),
                    child: Center(
                      child: Column(
                        children: [
                          const SizedBox(
                            height: 20,
                          ),
                          Align(
                            alignment: Alignment.topCenter,
                            child: Assets.icons.profileNoData.image(width: 150),
                          ),
                          Text(
                            'No Data',
                            style: TextStyle(
                              color: const Color(0xff000000).withOpacity(0.3),
                              fontWeight: FontWeight.normal,
                              fontSize: 16,
                            ),
                            textAlign: TextAlign.left,
                            overflow: TextOverflow.ellipsis,
                            maxLines: 1,
                          ),
                          const SizedBox(
                            height: 100,
                          ),
                        ],
                      ),
                    ),
                  ),
                SizedBox(
                  height: MediaQuery.of(context).padding.bottom,
                ),
              ],
            )
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  void didUpdateWidget(AfMinePage oldWidget) {
    super.didUpdateWidget(oldWidget);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }
}

class GiftMineCell extends StatelessWidget {
  const GiftMineCell({Key? key, this.type = 0}) : super(key: key);

  final int type;

  Widget get image {
    switch (type) {
      case 0:
        return Assets.icons.iconGiftsLeft.image();
      case 1:
        return Assets.icons.iconGiftsMid.image();
      default:
        return Assets.icons.iconGiftsRight.image();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 12),
          child: AspectRatio(
            aspectRatio: 1,
            child: image,
          ),
        ),
        const Align(
          alignment: Alignment.center,
          child: Text(
            '0',
            style: TextStyle(
              color: Color(0xff6B770B),
              fontWeight: FontWeight.normal,
              fontSize: 18,
            ),
            textAlign: TextAlign.center,
            overflow: TextOverflow.ellipsis,
            maxLines: 1,
          ),
        )
      ],
    );
  }
}
